package com.abaaba.project2.controller;

import com.abaaba.project2.aspect.Log;
import com.abaaba.project2.bean.bo.AdminBo;
import com.abaaba.project2.bean.template.TemplateAdminInfo;
import com.abaaba.project2.bean.vo.AdminInfoVo;
import com.abaaba.project2.bean.vo.BaseRespVo;

import com.abaaba.project2.service.AdminAuthService;
import com.abaaba.project2.shiro.Token.CustomToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;

@RestController
@RequestMapping("/admin/auth")
public class AdminAuthController {

    @Autowired
    AdminAuthService adminAuthService;

    @RequestMapping("/login")
    @Log
    public BaseRespVo adminLogin(@RequestBody AdminBo adminBo)
    {
        Subject subject = SecurityUtils.getSubject();

        CustomToken customToken = new CustomToken(adminBo.getUsername(),adminBo.getPassword(),"admin");

        try {
            subject.login(customToken);

            return BaseRespVo.ok(subject.getSession().getId());
        }
        catch (Exception e)
        {
            return BaseRespVo.fail("账号或密码错误");
        }

    }

    @RequestMapping("/info")
    public BaseRespVo adminInfo()
    {
        //虽然前台传了参数，但实际上是不需要的，因为登陆后已经保存了sessionid
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();

        AdminInfoVo adminInfoVo = adminAuthService.getAdminInfo(username);

        return BaseRespVo.ok(adminInfoVo);
    }

    @RequestMapping("/logout")
    @Log
    public BaseRespVo adminLogout()
    {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();

        return BaseRespVo.ok();
    }

}
